import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/userLogin/login/Login.vue'
import Register from '@/views/userLogin/register/Register.vue'
import Home from '@/views/home/Home.vue'
import Publish from '@/views/publish/Publish.vue'
import User from '@/views/user/User'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [{
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/register',
        name: 'register',
        component: Register
    },
    {
        path: '/',
        name: 'home',
        component: Home
    },
    {
        path: '/my',
        name: 'my',
        component: User
    },
    {
        path: '/history',
        name: 'history',
        component: () =>
            import ('@/views/user/history/History.vue')
    },
    {
        path: '/mypublic',
        name: 'mypublic',
        component: () =>
            import ('@/views/user/my_public/MyPublic.vue')
    },
    {
        path: '/publish',
        name: 'publish',
        component: Publish,
        // beforeEnter: (to, from, next) => {
        //     // let token = localStorage.getItem('token')
        //     // if (!token) {
        //     //     Toast('登录才能发布精彩内容哦')
        //     //     next('/login')
        //     // }
        // }
    }, {
        path: '/userdata',
        name: 'userdata',
        component: () =>
            import ('@/views/user/UserData.vue')
    }, {
        path: '/article',
        name: 'article',
        component: () =>
            import ('@/views/home/Article.vue')
    }, {
        path: '/search',
        name: 'search',
        component: () =>
            import ('@/views/search/Search.vue'),
        // children: [{
        //     path: 'searchlist',
        //     component: () =>
        //         import ('@/views/search/SearchList.vue'),
        // }]
    }


]

const router = new VueRouter({
    routes
})


router.beforeEach((to, from, next) => {
    if (to.path == '/login' || to.path == '/register') {
        next()
    } else {
        if (to.path == '/publish') {
            let token = localStorage.getItem('token');
            if (token == null || token === '') {
                Toast('请先登录')
                next('/login')
            } else {
                next()
            }
        } else {
            next()
        }

    }
})


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}

export default router